

interface Config {
	url:string
	data?:object,
	method?:'GET'|'POST'|'PUT'|'DELETE',
	headers?:object,
	loading?:Boolean
}
let host = ''
if(import.meta.env.VITE_APP_ENV == 'development'){
	host = '' // 开发环境
}else{
	host = '' // 生产环境
}
interface DataVo {
	code:number,msg:string,data:any,rows:any[],total:number
}
export default function request<T = DataVo>(config:Config):Promise<T>{
	return new Promise((resolve, reject) => {
		const {userToken,setToken,setLoading} = useUserStore()
		let header = {
			Authorization:''
		}
		if(userToken){
			header.Authorization = 'Bearer '+userToken
		}
		if(config.headers) header = Object.assign(header,config.headers)
		setLoading(true)
		uni.request({
			url: host + config.url,
			data:config.data,
			header,
			method:config.method || 'GET',
			timeout:10000,
			success: res => {
				console.log('result',{
					url:config.url,
					data:res.data
				});
				const data:DataVo = res.data as any
				if(res.statusCode!=200) {
					uni.showToast({
						title:'网络异常',
						icon:'error',
						duration:2000
					})
					return reject(res.data)
				}
				if(data.code == 401) {
					setToken('')
					uni.navigateTo({
						url:'/pages/login/login'
					})
					return reject(res.data)
				}
				if(data.code!=200) {
					if(data.msg.length>10){
						showModal('提示',data.msg,false)
					}else uni.showToast({
						title:data.msg,
						icon:'error',
						duration:1500
					})
					return reject(res.data)
				}
				resolve(data as T)
			},
			fail: error => {
				reject(error)
				uni.showToast({
					title:'请求失败！',
					icon:'fail'
				})
			},
			complete:()=> setLoading(false)
		})
	}) as Promise<T>
}

export function http<T = Promise<any>>(url:string, data = {}, method = 'POST', headers={}, loading = true):Promise<T>{
	return request({
		url,
		data,
		method:method as Config['method'],
		headers,
		loading
	})
}
/*
 * 文件上传
 * @param {String} filePath 上传文件路径
 * @returns {Promise}
 */
interface FileVo{
	fileId:number
	url:string
}
export function uploadFiles(filePath:string, name = 'file'):Promise<FileVo> {
	return new Promise((resolve, reject) => {
		const {userToken} = useUserStore()
		let header = {
			Authorization:'Bearer '+userToken
		}
		uni.showLoading({
			title: '上传中...',
			mask: true
		})
		uni.uploadFile({
			url: host + '/upload',
			filePath,
			header,
			name: name || 'file',
			timeout:10000,
			success: res => {
				try{
					const data = JSON.parse(res.data)
					if(data.code!=200) {
						uni.showToast({
							title:'上传失败'
						})
						return reject(new Error('error'))
					}
					resolve(data)
				}catch(e){
					reject(e)
				}
			},
			fail: error => {
				uni.showToast({
					title:'上传失败'
				})
				reject(error)
			},
			complete:()=> uni.hideLoading()
		})
	})
}